package org.ccspace;

import org.ccspace.calendar.Event;
import org.hibernate.Session;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class EventManager
{

	public static void main(String[] args)
	{
		EventManager mgr = new EventManager();
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		
		List<Event> events = mgr.listEvents();
		for (Event event : events)
		{
			System.out.println(event.getId() + " " + event.getTitle() + " " + event.getDate());
		}
		
		try
		{
			while (true)
			{
				String title = in.readLine();
				mgr.createAndStoreEvent(title, new Date());
			}
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		HibernateUtil.getSessionFactory().close();
		
	}
	
	private List<Event> listEvents() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<Event> result = session.createQuery("from Event").list();
        session.getTransaction().commit();
        return result;
    }

	private void createAndStoreEvent(String title, Date theDate)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Event theEvent = new Event();
		theEvent.setTitle(title);
		theEvent.setDate(theDate);
		session.save(theEvent);

		session.getTransaction().commit();
	}

}